<template>
  <div>
    <a-card title="打印销售单详情">
      <div>
        <label for="font-size" style="margin-left: 8px;font-size:20px">字体大小：</label>
        <input
          id="font-size"
          v-model="fontSize"
          type="number"
          min="10"
          max="30"
          style="margin-left: 8px;font-size:20px"
          @change="applyFontStyles"
        />
        <label for="font-bold" style="margin-left: 8px;font-size:20px">加粗：</label>
        <input
          id="font-bold"
          type="checkbox"
          @change="applyFontStyles"
          v-model="isBold"
        />
        <!-- 设置按钮 -->
        <!-- <a-button
          type="primary"
          style="margin-left: 8px"
          @click="applyFontStyles"
          >应用字体样式</a-button
        > -->
      </div>
      <a-button
        ref="printButton"
        slot="extra"
        type="primary"
        style="margin-left: 8px"
        v-print="'#printContent'"
      >
        <a-icon type="printer" />打印</a-button
      >
      <a-button
        slot="extra"
        type="primary"
        ghost
        @click="
          () => {
            this.$router.go(-1);
          }
        "
      >
        <a-icon type="left" />返回</a-button
      >
      <div style="text-align: center" v-if="info.sales_account_items">
        <section id="printContent" style="display: inline-block">
          <a-spin :spinning="loading">
            <!-- <img id="barcode" style="float: right" /> -->
            <div style="text-align: center; font-weight: bolder">
              <h3>
                <span style="font-weight: bolder; font-size: 26px"
                  >温州从进塑料薄膜有限公司产品销售单</span
                >
              </h3>
            </div>
            <div>
              <span style="float: left; color: black"
                >销售编号：{{ info.number }}</span
              >

              <span style="margin-left: 100px; float: left; color: black"
                >手机:13868836559、18072155333</span
              >
              <span style="margin-left: 150px; float: left; color: black"
                >备注：{{ info.remark }}</span
              >
            </div>
            <table
              id="dishihuizong"
              width="100%"
              border="1"
              cellspacing="1"
              cellpadding="4"
              bgcolor="#fefefe"
              align="center"
              style="margin-bottom: 1px"
            >
              <tr>
                <td width="4.9%" class="btbg head titfont">客户</td>
                <td width="27%" class="btbg head" style="text-align: left">
                  {{ info.client_name }}
                </td>
                <td width="5%" class="btbg head titfont">电话</td>
                <td width="10%" class="btbg head">{{ info.client_phone }}</td>
                <td width="7%" class="btbg head titfont">经手人</td>
                <td width="7%" class="btbg head">{{ info.handler_name }}</td>
                <td width="8%" class="btbg head titfont">录单时间</td>
                <td width="18%" class="btbg head">{{ info.handle_time }}</td>
              </tr>
            </table>
            <!-- <a-divider orientation="left" style="margin-top: 30px;">结算账户信息</a-divider>
          <a-table
            rowKey="id"
            size="middle"
            :columns="columnsAccount"
            :data-source="info.sales_account_items"
            :pagination="false" /> -->
            <!-- <a-divider orientation="left" style="margin-top: 30px;">产品信息</a-divider> -->
            <a-table
              class="my-table"
              bordered
              rowKey="id"
              size="middle"
              :columns="columns_select"
              :data-source="info.sales_goods_items"
              :pagination="false"
            />
            <table
              id="dishihuizong"
              width="100%"
              border="1"
              cellspacing="1"
              cellpadding="1"
              bgcolor="#fefefe"
              align="center"
              style="margin-top: 1px"
            >
              <tr>
                <td width="12%" class="font-center titfont">银行卡信息</td>
                <td width="88%" colspan="5" class="font-left">
                  开户行：中国农业银行
                  <span class="span-fenge">|</span
                  ><span class="span-fenge"> 户名：刘从进</span>
                  <span class="span-fenge">|</span
                  ><span class="span-fenge"
                    >卡号：6228 4803 3820 4880 078
                  </span>
                </td>
              </tr>
              <tr>
                <td width="18%" class="font-center titfont">
                  总计金额（大写）
                </td>
                <td width="30%" class="font-center dxfont">
                  {{ convertCurrency(Math.round(info.total_amount)) }}
                </td>
                <td
                  width="13"
                  class="titfont"
                  style="text-align: left; text-indent: 10px"
                >
                  收货人：
                </td>
              </tr>
            </table>
          </a-spin>
        </section>
      </div>
    </a-card>
  </div>
</template>

<script>
import _ from "lodash";
import { saleOrderDetail } from "@/api/sale";
import { convertCurrency } from "@/utils/functions";
import {
  canshu,
  columns_dagong_detail,
  rules,
  columnsAccount,
  calzhong_dg,
  calmianji_dg,
  calclAmount,
  caljgAmount_dg,
  callingjianDj_dg,
  calljtotalAmount_dg,
  calshifuAmount_dg,
} from "@/views/sale/saleCreate/js/data";
import JsBarcode from "jsbarcode";

export default {
  data() {
    return {
      fontSize: 16, // 默认字体大小
      isBold: true, // 默认加粗
      loading: false,
      materialLoading: false,
      // receiptOrder: undefined,
      info: {},
      columns_dagong_detail,
      columns_dagong_data: [],
      is_dagong_table: false,
      showTz: false,
      columns_select: [],
      columns: [
        {
          title: () => {
            return <span class="weight-cell">序号</span>; // 将“商品名称”加粗
          },
          dataIndex: "index",
          key: "index",
          width: 42,
          customRender: (value, item, index) => {
            let v = item.isTotal ? "合计" : index + 1;
            return <span class="weight-cell">{v}</span>;
          },
        },
        {
          title: () => {
            return <span class="weight-cell">商品名称</span>; // 将“商品名称”加粗
          },
          dataIndex: "name",
          key: "name",
          width: 80,
          align: "center",
          customRender: (value) => {
            return <span class="weight-cell">{value}</span>;
          },
        },
        {
          title: () => {
            return <span class="weight-cell">型号尺寸</span>; // 将“商品名称”加粗
          },
          dataIndex: "specification",
          key: "specification",
          width: 80,
          align: "center",
          customRender: (value) => {
            return <span class="weight-cell">{value}</span>;
          },
        },
        {
          title: () => {
            return <span class="weight-cell">件数</span>; // 将“商品名称”加粗
          },
          dataIndex: "quantity",
          key: "quantity",
          width: 60,
          align: "center",
          customRender: (value) => {
            return <span class="weight-cell">{value}</span>;
          },
        },
        {
          title: () => {
            return <span class="weight-cell">材料费</span>; // 将“商品名称”加粗
          },
          dataIndex: "clf",
          key: "clf",
          align: "center",
          children: [
            {
              title: () => {
                return <span class="weight-cell">重量(市斤)</span>; // 将“商品名称”加粗
              },
              dataIndex: "total_weight",
              key: "total_weight",
              width: 100,
              align: "center",
              customRender: (value) => {
                return <span class="weight-cell">{value}</span>;
              },
            },
            {
              title: () => {
                return <span class="weight-cell">单价</span>; // 将“商品名称”加粗
              },
              dataIndex: "material_unit_price",
              key: "material_unit_price",
              width: 45,
              align: "center",
              customRender: (value) => {
                return <span class="weight-cell">{value}</span>;
              },
            },
            {
              title: () => {
                return <span class="weight-cell">金额</span>; // 将“商品名称”加粗
              },
              dataIndex: "material_amount",
              key: "material_amount",
              width: 70,
              align: "center",
              customRender: (value, item) => {
                return item.id ? (
                  <span class="weight-cell">{Math.round(value)}</span>
                ) : (
                  ""
                );
              },
            },
          ],
        },
        {
          title: () => {
            return <span class="weight-cell">烫工费</span>; // 将“商品名称”加粗
          },
          dataIndex: "jgf",
          key: "jgf",
          align: "center",
          children: [
            {
              title: () => {
                return <span class="weight-cell">条数</span>; // 将“商品名称”加粗
              },
              dataIndex: "total_strip_count",
              key: "total_strip_count",
              width: 70,
              align: "center",
              customRender: (value) => {
                return <span class="weight-cell">{value}</span>;
              },
            },
            {
              title: () => {
                return <span class="weight-cell">单价</span>; // 将“商品名称”加粗
              },
              dataIndex: "ironing_unit_price",
              key: "ironing_unit_price",
              width: 60,
              align: "center",
              customRender: (value) => {
                return <span class="weight-cell">{value}</span>;
              },
            },
            {
              title: () => {
                return <span class="weight-cell">金额</span>; // 将“商品名称”加粗
              },
              dataIndex: "ironing_amount",
              key: "ironing_amount",
              width: 70,
              align: "center",
              customRender: (value, item) => {
                return item.id ? (
                  <span class="weight-cell">{Math.round(value)}</span>
                ) : (
                  ""
                );
              },
            },
          ],
        },
        {
          title: () => {
            return <span class="weight-cell">总金额</span>; // 将“商品名称”加粗
          },
          dataIndex: "total_amount",
          key: "total_amount",
          width: 75,
          align: "center",
          customRender: (value, item) => {
            return item.id ? (
              <span class="weight-cell">{Math.round(value)}</span>
            ) : (
              ""
            );
          },
        },
        {
          title: () => {
            return <span class="weight-cell">备注</span>; // 将“商品名称”加粗
          },
          dataIndex: "notes",
          key: "notes",
          width: 80,
          align: "center",
        },
      ],
      columnsAccount: [
        {
          title: "序号",
          dataIndex: "index",
          key: "index",
          width: 45,
          customRender: (value, item, index) => {
            return item.isTotal ? "合计" : index + 1;
          },
        },
        {
          title: "结算账户",
          dataIndex: "account_name",
          key: "account_name",
          width: 200,
        },
        {
          title: "付款金额",
          dataIndex: "collection_amount",
          key: "collection_amount",
          width: 200,
        },
      ],
    };
  },
  methods: {
    // 从 localStorage 获取字体设置
    loadFontSettings() {
      const savedSettings = localStorage.getItem("fontSettings");
      if (savedSettings) {
        const settings = JSON.parse(savedSettings);
        this.fontSize = settings.fontSize || 16; // 如果没有设置，使用默认值
        this.isBold = settings.isBold !== undefined ? settings.isBold : true; // 如果没有设置，使用默认值
        this.applyFontStyles(); // 应用设置
      }
    },

    // 应用字体样式
    applyFontStyles() {
      const weightCellStyle = {
        fontSize: `${this.fontSize}px`, // 字体大小来自用户输入
        fontWeight: this.isBold ? "bold" : "normal", // 是否加粗
      };

      // 更新动态样式
      this.updateWeightCellStyle(weightCellStyle);

      // 保存到 localStorage
      this.saveFontSettings();
    },

    // 保存字体设置到 localStorage
    saveFontSettings() {
      const settings = {
        fontSize: this.fontSize,
        isBold: this.isBold,
      };
      localStorage.setItem("fontSettings", JSON.stringify(settings));
    },

    // 更新 .weight-cell 样式
    updateWeightCellStyle(styleObj) {
      const styleElement = document.createElement("style");
      styleElement.innerHTML = `
      .weight-cell {
        font-size: ${styleObj.fontSize} !important;
        font-weight: ${styleObj.fontWeight} !important;
      }
    `;
      document.head.appendChild(styleElement);
    },

    calculateColumnWidths() {
      const columnsToCheck = ["goods_name", "specification"]; // 对应要动态调整宽度的列的 dataIndex
      const tableData = this.info.sales_goods_items;

      const columnWidths = {};
      // 获取页面缩放比例
      const zoom = window.innerWidth / document.documentElement.clientWidth;

      // 遍历每一行数据
      tableData.forEach((row) => {
        columnsToCheck.forEach((columnKey) => {
          const content = row[columnKey];
          const element = document.createElement("span");
          element.style.visibility = "hidden";
          element.textContent = content;
          document.body.appendChild(element);
          const width = element.offsetWidth;
          document.body.removeChild(element);
          // 根据缩放比例调整计算的宽度
          const adjustedWidth = width * zoom;

          if (columnKey === "goods_name" || columnKey === "specification") {
            columnWidths[columnKey] = Math.max(80, adjustedWidth + 50);
          } else {
            if (
              !columnWidths[columnKey] ||
              adjustedWidth > columnWidths[columnKey]
            ) {
              columnWidths[columnKey] = adjustedWidth;
            }
          }
        });
      });

      return columnWidths;
    },
    unitTypeChange(unitType) {
      this.columns_dagong_data = _.cloneDeep(columns_dagong_detail);
      if (!unitType) {
        this.columns_dagong_data[2].children.splice(4, 1); //根据用料计量默认为重量删除面积
        this.columns_dagong_data[2].title = "用料(长宽厚:mm,面积:dm²)";
      } else {
        this.columns_dagong_data[2].children.splice(5, 1); //根据用料计量默认为重量删除面积
        this.columns_dagong_data[2].title = "用料(长宽厚:mm,重:kg)";
      }
    },
    NPround2(val) {
      return NP.round(val, 2);
    },
    convertCurrency(money) {
      return convertCurrency(money);
    },
    //  getJsBarcode(number) {
    //     JsBarcode("#barcode", number, {
    //       lineColor: '#000',
    //       width: 2,
    //       height: 40,
    //       displayValue: true
    //     });
    //   },
    getgoodsData(sales_goods_items) {
      // 统计合计
      let totalclAmount = 0,
        //普通表格部分
        material_amount = 0,
        ironing_amount = 0,
        total_weight = 0,
        total_strip_count = 0,
        quantity = 0,
        total_amount = 0;
      for (let item of sales_goods_items) {
        material_amount = NP.plus(material_amount, item.material_amount);
        ironing_amount = NP.plus(ironing_amount, item.ironing_amount);
        total_weight = NP.plus(total_weight, item.total_weight);
        total_strip_count = NP.plus(total_strip_count, item.total_strip_count);
        quantity = NP.plus(quantity, item.quantity);
        total_amount = NP.plus(total_amount, item.total_amount);
      }

      return {
        material_amount: Math.round(material_amount),
        ironing_amount: Math.round(ironing_amount),
        total_weight,
        total_strip_count,
        quantity,
        total_amount: Math.round(total_amount),
      };
    },
    initData() {
      this.loading = true;
      return saleOrderDetail({ id: this.$route.query.id })
        .then((data) => {
          this.info = data;
          this.is_dagong_table = data.sales_goods_items[0].is_dagong_table;
          let unitType = data.sales_goods_items[0].yongliaojl;
          this.unitTypeChange(unitType);
          this.columns_select = this.is_dagong_table
            ? this.columns_dagong_data
            : this.columns;

          // 获取并应用动态计算的列宽
          const columnWidths = this.calculateColumnWidths();
          this.columns_select.forEach((column) => {
            if (columnWidths[column.dataIndex]) {
              // 增加一定的宽度余量，这里增加 10 像素，可根据实际情况调整
              column.width = columnWidths[column.dataIndex] + 10;
            }
          });
          this.info.sales_account_items = [
            ...this.info.sales_account_items,
            {
              id: "-1",
              isTotal: true,
              collection_amount: this.info.collection_amount,
            },
          ];
          let Amount = this.getgoodsData(this.info.sales_goods_items);
          this.info.sales_goods_items = [
            ...this.info.sales_goods_items,
            {
              id: "-1",
              isTotal: true,
              name: "",
              // sales_quantity: totalQuantity,
              // totalAmount: `${totalAmount} * ${this.form.discount}% = ${NP.times(
              //   totalAmount,
              //   this.form.discount || 0,
              //   0.01
              // )}`,
              material_amount: Amount.material_amount,
              ironing_amount: Amount.ironing_amount,
              total_weight: Amount.total_weight,
              total_strip_count: Amount.total_strip_count,
              quantity: Amount.quantity,
              total_amount: Amount.total_amount,
            },
          ];
          // this.getJsBarcode(data.number)
        })
        .finally(() => {
          this.loading = false;
        });
    },
    simulatePrintButtonClick() {
      // 使用 Vue 的 $refs 来获取打印按钮元素
      const printButton = this.$refs.printButton;
      if (printButton) {
        // 创建并触发点击事件
        const event = new MouseEvent("click", {
          view: window,
          bubbles: true,
          cancelable: true,
        });
        printButton.$el.dispatchEvent(event);
      } else {
        console.error("未找到打印按钮");
      }
    },
  },
  mounted() {
    this.initData().then(() => {
      // 加载用户保存的字体设置
      this.loadFontSettings();
      this.$nextTick(() => {
        this.simulatePrintButtonClick(); // 数据加载完毕后模拟点击打印按钮
      });
    });
  },
};
</script>
<style scoped>
::v-deep .ant-table-thead > tr > th {
  color: rgb(0, 0, 0) !important;
  background: #f9f9f9 !important;
  border: solid 1px #000000 !important;
  padding: 1px !important;
}
::v-deep .ant-table-tbody > tr > td {
  color: rgb(0, 0, 0) !important;
  border: solid 1px #000000 !important;
  padding: 1px !important;
}
.head {
  padding: 1px !important;
}
::v-deep table {
  /* 边框合并 */
  color: rgb(0, 0, 0) !important;
  border-collapse: collapse !important;
}
.font-left {
  padding-left: 20px;
  text-align: left;
}
.span-fenge {
  padding-left: 10px;
}
::v-deep #dishihuizong td {
  height: 30px;
}
</style>
